#include "FileReceiver.h"
#include "MD5.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <netinet/in.h>
#include <stdint.h>
#include <vector>
#include <map>
#include "FitsConverter.h"

#define CHUNK_SIZE 4096
#define WRITE_BUF_SIZE (256 * 1024)

static void flush_write_buffer(FILE *fp, unsigned char *write_buf, size_t *write_buf_used) {
    if (*write_buf_used > 0) {
        fwrite(write_buf, 1, *write_buf_used, fp);
        *write_buf_used = 0;
    }
}

// 单文件构造
FileReceiver::FileReceiver(const std::string& save_path, int listen_port)
    : save_path_(save_path), listen_port_(listen_port) {}

// 多文件构造
FileReceiver::FileReceiver(const std::vector<std::string>& save_paths, int listen_port)
    : save_paths_(save_paths), listen_port_(listen_port) {}

// 单文件UDP接收
void FileReceiver::recvUDP() {
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        perror("socket error");
        exit(1);
    }
    int bufsize = 8 * 1024 * 1024;
    setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize));
    setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize));
    struct sockaddr_in local_addr, src_addr;
    socklen_t addrlen = sizeof(src_addr);
    memset(&local_addr, 0, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    local_addr.sin_port = htons(listen_port_);
    if (bind(sock, (struct sockaddr*)&local_addr, sizeof(local_addr)) < 0) {
        perror("bind error");
        close(sock);
        exit(1);
    }
    unsigned int expected_seq = 0;
    size_t received_packets = 0;
    size_t lost_packets = 0;
    unsigned char *write_buf = (unsigned char*)malloc(WRITE_BUF_SIZE);
    size_t write_buf_used = 0;
    FILE* fp = fopen(save_path_.c_str(), "wb");
    if (!fp) {
        perror("Failed to open output file");
        close(sock);
        exit(1);
    }
    while (1) {
        unsigned char recvbuf[CHUNK_SIZE + 4];
        ssize_t recvd = recvfrom(sock, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*)&src_addr, &addrlen);
        if (recvd < 4) continue;
        unsigned int seq;
        memcpy(&seq, recvbuf, 4);
        if (seq == 0xFFFFFFFF) break;
        size_t data_len = recvd - 4;
        if (seq == expected_seq) {
            if (write_buf_used + data_len > WRITE_BUF_SIZE) {
                flush_write_buffer(fp, write_buf, &write_buf_used);
            }
            memcpy(write_buf + write_buf_used, recvbuf + 4, data_len);
            write_buf_used += data_len;
            expected_seq++;
            received_packets++;
        } else if (seq > expected_seq) {
            lost_packets += (seq - expected_seq);
            expected_seq = seq + 1;
            if (write_buf_used + data_len > WRITE_BUF_SIZE) {
                flush_write_buffer(fp, write_buf, &write_buf_used);
            }
            memcpy(write_buf + write_buf_used, recvbuf + 4, data_len);
            write_buf_used += data_len;
            received_packets++;
        }
    }
    flush_write_buffer(fp, write_buf, &write_buf_used);
    free(write_buf);
    printf("Receive finished.\n");
    printf("Total packets received: %zu\n", received_packets);
    printf("Lost packets: %zu\n", lost_packets);
    if (received_packets + lost_packets > 0) {
        double loss_rate = 100.0 * lost_packets / (received_packets + lost_packets);
        printf("Packet loss rate: %.2f%%\n", loss_rate);
    }
    fclose(fp);
    close(sock);
}

// 多文件多bufferUDP接收
void FileReceiver::recvMultiUDP() {
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        perror("socket error");
        exit(1);
    }
    int bufsize = 8 * 1024 * 1024;
    setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize));
    setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize));
    struct sockaddr_in local_addr, src_addr;
    socklen_t addrlen = sizeof(src_addr);
    memset(&local_addr, 0, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    local_addr.sin_port = htons(listen_port_);
    if (bind(sock, (struct sockaddr*)&local_addr, sizeof(local_addr)) < 0) {
        perror("bind error");
        close(sock);
        exit(1);
    }
    const int file_count = FitsConverter::kNumBins;
    size_t width = 512, height = 512; // 可根据实际情况调整
    size_t size = width * height;

    // 初始化FitsConverter并分配内存
    FitsConverter converter("output.fits");
    converter.allocateData(width, height);
    converter.setBinName(0, "BIN1");
    converter.setBinName(1, "BIN2");
    converter.setBinName(2, "BIN3");
    converter.setBinName(3, "BIN4");

    size_t binOffset[file_count] = {0, 0, 0, 0};
    int finished[file_count] = {0,0,0,0};
    int finished_count = 0;
    while (finished_count < file_count) {
        unsigned char recvbuf[CHUNK_SIZE + 1 + 4];
        ssize_t recvd = recvfrom(sock, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*)&src_addr, &addrlen);
        if (recvd < 1 + 4) continue;
        int file_id = recvbuf[0];
        if (file_id < 0 || file_id >= file_count) continue;
        unsigned int seq;
        memcpy(&seq, recvbuf + 1, 4);
        if (seq == 0xFFFFFFFF) {
            if (!finished[file_id]) { finished[file_id] = 1; finished_count++; }
            continue;
        }
        size_t data_len = recvd - (1 + 4);
        // 直接写入FitsConverter的内存
        uint16_t* dest = converter.binData_[file_id];
        if (dest && binOffset[file_id] + data_len/2 <= size) {
            memcpy(dest + binOffset[file_id], recvbuf + 1 + 4, data_len);
            binOffset[file_id] += data_len / 2;
        }
    }
    printf("Multi-file UDP receive finished. Generating FITS...\n");
    close(sock);
    converter.writeFits();
    printf("FITS file generated: output.fits\n");
}

void FileReceiver::recvTCP() {
    int listen_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (listen_sock < 0) {
        perror("socket error");
        exit(1);
    }
    struct sockaddr_in local_addr, client_addr;
    socklen_t addrlen = sizeof(client_addr);
    memset(&local_addr, 0, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    local_addr.sin_port = htons(listen_port_);
    if (bind(listen_sock, (struct sockaddr*)&local_addr, sizeof(local_addr)) < 0) {
        perror("bind error");
        close(listen_sock);
        exit(1);
    }
    if (listen(listen_sock, 1) < 0) {
        perror("listen error");
        close(listen_sock);
        exit(1);
    }
    printf("Waiting for TCP connection on port %d...\n", listen_port_);
    int conn_sock = accept(listen_sock, (struct sockaddr*)&client_addr, &addrlen);
    if (conn_sock < 0) {
        perror("accept error");
        close(listen_sock);
        exit(1);
    }
    uint64_t filesize = 0;
    ssize_t r = recv(conn_sock, &filesize, sizeof(filesize), MSG_WAITALL);
    if (r != sizeof(filesize)) {
        printf("Failed to receive file size!\n");
        close(conn_sock);
        close(listen_sock);
        return;
    }
    size_t total_received = 0;
    unsigned char buf[CHUNK_SIZE];
    unsigned char *write_buf = (unsigned char*)malloc(WRITE_BUF_SIZE);
    size_t write_buf_used = 0;
    FILE* fp = fopen(save_path_.c_str(), "wb");
    if (!fp) {
        perror("Failed to open output file");
        close(conn_sock);
        close(listen_sock);
        exit(1);
    }
    while (total_received < filesize) {
        size_t to_read = (filesize - total_received > CHUNK_SIZE) ? CHUNK_SIZE : (filesize - total_received);
        ssize_t recvd = recv(conn_sock, buf, to_read, MSG_WAITALL);
        if (recvd <= 0) break;
        if (write_buf_used + recvd > WRITE_BUF_SIZE) {
            flush_write_buffer(fp, write_buf, &write_buf_used);
        }
        memcpy(write_buf + write_buf_used, buf, recvd);
        write_buf_used += recvd;
        total_received += recvd;
    }
    flush_write_buffer(fp, write_buf, &write_buf_used);
    free(write_buf);
    printf("TCP receive finished. Total bytes: %zu\n", total_received);
    unsigned char md5_recv[16];
    ssize_t md5len = recv(conn_sock, md5_recv, 16, MSG_WAITALL);
    if (md5len != 16) {
        printf("Failed to receive MD5 checksum!\n");
    } else {
        fclose(fp);
        fp = fopen(save_path_.c_str(), "rb");
        if (!fp) {
            printf("Failed to open received file for MD5 check!\n");
        } else {
            MD5 ctx;
            ctx.reset();
            unsigned char filebuf[4096];
            size_t n;
            while ((n = fread(filebuf, 1, sizeof(filebuf), fp)) > 0) {
                ctx.update(filebuf, n);
            }
            unsigned char md5_local[16];
            ctx.final(md5_local);
            int match = memcmp(md5_local, md5_recv, 16) == 0;
            printf("MD5 check: %s\n", match ? "PASS" : "FAIL");
        }
    }
    fclose(fp);
    close(conn_sock);
    close(listen_sock);
} 